import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { loginRequest, getUserInfoById, getUserRouterList } from '@/service/login'
import { localCache, sessionCache } from '@/utils/storage'
import { message } from 'antd'
import type { MainStore } from './types'

export const useMainStore = create(
	devtools<MainStore>((set) => ({
		token: '',
		userInfo: {},
		userMenus: [],
		headerTags: [],

		loginAction: async (payload) => {
			// 账号登录
			const login = await loginRequest(payload)
			const token = login.data?.token
			if (token) {
				localCache.setItem('token', token)
			}
			// 获取用户详细信息
			const userInfo = await getUserInfoById({ id: login.data.id })
			localCache.setItem('userInfo', userInfo.data)
			// 获取用户对应权限路由
			const userMenus = await getUserRouterList({ id: login.data.id })
			// if (userMenus.data.length) registerRouters(userMenus.data)
			localCache.setItem('userMenus', userMenus.data)
			message.success('登录完成')

			set(() => ({
				token: login.data.token,
				userInfo: userInfo.data,
				userMenus: userMenus.data
			}))
		},
		// 储存headerTags
		addRouteToTags: (tag) => {
			set((state) => {
				const tags = [...state.headerTags]
				const find = tags.find((item) => item.path === tag.path)
				if (!find) {
					tags.push(tag)
					sessionCache.setItem('headerTags', tags)
				}
				return {
					headerTags: tags
				}
			})
		},
		// 修改tags
		updateHeaderTags: (list: MainStore['headerTags']) => {
			set(() => ({ headerTags: list }))
		},
		// 获取缓存数据
		loadLocalStorage: () => {
			const token = localCache.getItem('token') ?? ''
			const userInfo = localCache.getItem('userInfo') ?? {}
			const userMenus = localCache.getItem<MainStore['userMenus']>('userMenus') ?? []
			// if (userMenus.length) registerRouters(userMenus)
			const headerTags = sessionCache.getItem('headerTags') ?? [{ title: '首页', path: '/home' }]

			set(() => ({
				token,
				userInfo,
				userMenus,
				headerTags
			}))
		}
	}))
)
